package com.xique.client.service.biz.service.impl;

import com.xique.client.api.domain.ClientUserInfo;
import com.xique.client.bean.domain.Client;
import com.xique.client.bean.domain.ClientLoginInfo;
import com.xique.client.service.biz.service.IClientLoginInfoBizService;
import com.xique.client.service.service.IClientLoginInfoService;
import com.xique.client.service.service.IClientService;
import com.xique.client.service.service.IClientUserInfoService;
import com.xique.common.core.constant.Constants;
import com.xique.common.core.domain.R;
import com.xique.common.core.utils.ServletUtils;
import com.xique.common.core.utils.ip.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author shd
 * @create 2021/7/22 9:45
 */
@Service
public class ClientLoginInfoBizServiceImpl implements IClientLoginInfoBizService {

    @Autowired
    private IClientUserInfoService clientUserInfoService;

    @Autowired
    private IClientLoginInfoService clientLoginInfoService;

    @Autowired
    private IClientService clientService;

    @Override
    public R<Boolean> addLoginInfo(Long clientId, String loginName, String status, String message) {

        ClientUserInfo userInfo = clientUserInfoService.selectClientUserByLoginName(loginName);

        Client client = clientService.selectClientById(clientId);

        ClientLoginInfo loginInfo = new ClientLoginInfo();
        loginInfo.setLoginName(loginName);
        loginInfo.setStatus(status);
        loginInfo.setMsg(message);
        loginInfo.setParkId(userInfo.getParkId());
        loginInfo.setUserId(userInfo.getId());
        loginInfo.setUserName(userInfo.getUserName());
        loginInfo.setIpAddress(IpUtils.getIpAddr(ServletUtils.getRequest()));
        loginInfo.setClientId(client.getId());
        loginInfo.setClientName(client.getName());

        // 日志状态
        if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
            loginInfo.setStatus("0");
        } else if (Constants.LOGIN_FAIL.equals(status)) {
            loginInfo.setStatus("1");
        }

        int count = clientLoginInfoService.insertClientLoginInfo(loginInfo);
        if (count <= 0) {
            return R.fail("登录日志添加失败");
        }
        return R.ok();
    }

    @Override
    public R<Boolean> deleteClientUserInfo(Long clientId) {

        Client client = clientService.selectClientById(clientId);
        client.setId(clientId);
        client.setLoginUserName(null);
        client.setLoginUserId(null);
        client.setLoginTime(null);

        int count = clientService.updateClient(client);
        if (count <= 0) {
            return R.fail();
        }

        return R.ok();
    }
}
